import subprocess
import sys
import os


def run_git_command(command):
    try:
        result = subprocess.run(
            command,
            shell=True,
            check=True,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True,
        )
        return result.stdout
    except subprocess.CalledProcessError as e:
        print(f"错误: {e.stderr}")
        sys.exit(1)


def main():
    # 检查是否在Git仓库中
    try:
        subprocess.run(
            "git rev-parse --is-inside-work-tree",
            shell=True,
            check=True,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
        )
    except subprocess.CalledProcessError:
        print("错误: 当前目录不是Git仓库")
        sys.exit(1)

    # 获取提交信息
    if len(sys.argv) > 1:
        commit_message = " ".join(sys.argv[1:])
    else:
        commit_message = "Auto commit by script"

    # 执行Git操作
    print("正在添加所有更改...")
    run_git_command("git add .")

    print("正在提交更改...")
    run_git_command(f'git commit -m "{commit_message}"')

    print("正在推送至远程仓库...")
    current_branch = subprocess.check_output(
        "git branch --show-current", shell=True, text=True
    ).strip()
    run_git_command(f"git push origin {current_branch}")

    print("\n✅ 所有更改已成功同步到云端!")


if __name__ == "__main__":
    main()
